import { ref, unref, watch } from 'vue'

import { useComDesignStoreWithOut, getCustomComDesignInfo } from '@/store'

import {
  getNodeComEmits,
  BwComTypeEnum,
  type BwCustomComEmitInfoModel,
  type BwCustomComNodeEventInfoModel,
} from '@bitwit/base-com-render'

import type { BwCurNodeEventInfoModel } from './model'

export function useNodeEvent() {
  const designStore = useComDesignStoreWithOut()

  const curNodeId = ref<string>('')
  const curVisible = ref<boolean>(false)
  const curEventInfo = ref<Nullable<BwCurNodeEventInfoModel>>(null)
  const curNodeEventList = ref<Array<BwCurNodeEventInfoModel>>([])

  /** 初始化事件列表 */
  const initEventList = (
    data: Array<BwCustomComEmitInfoModel>,
    events: Array<BwCustomComNodeEventInfoModel>
  ) => {
    const list: Array<BwCurNodeEventInfoModel> = []

    if (Array.isArray(data) && data.length) {
      data.forEach((item) => {
        if (!item.isModel) {
          const curEvt = events.find((n) => n.eventCode === item.key)
          list.push({
            isExpand: true,
            eventCode: item.key,
            eventName: item.name ?? '',
            eventParams: item.params,
            callbackFun: curEvt?.callbackFun,
            callbackFunParams: curEvt?.callbackFunParams,
          })
        }
      })
    }
    curNodeEventList.value = list
  }

  /** 打开事件配置弹窗 */
  const onOpenEventModal = (item: BwCurNodeEventInfoModel) => {
    curEventInfo.value = item
    curVisible.value = true
  }

  /** 关闭事件配置弹窗回调函数 */
  const onEventModalOk = (data: BwCurNodeEventInfoModel) => {
    designStore.onChangeNodeEvent(unref(curNodeId), {
      eventName: data.eventName,
      eventCode: data.eventCode,
      eventParams: data.eventParams,
      callbackFun: data.callbackFun,
      callbackFunParams: data.callbackFunParams,
    })

    curVisible.value = false
  }

  watch(
    () => designStore.selectNodeEle,
    (newVal) => {
      if (newVal) {
        const nodeId = newVal.nodeId
        const comCode = newVal.comName
        const comType = newVal?.comType
        const events = newVal?.events ?? []

        curNodeId.value = nodeId
        if (comType === BwComTypeEnum.custom) {
          const appCode = newVal?.comAppCode
          if (appCode) {
            getCustomComDesignInfo(appCode, comCode).then((comInfo) => {
              const list = comInfo?.emits ?? []
              initEventList(list, events)
            })
          } else {
            curNodeEventList.value = []
          }
        } else {
          const list = getNodeComEmits(comCode)
          initEventList(list, events)
        }
      } else {
        curNodeEventList.value = []
      }
    },
    { deep: true, immediate: true }
  )

  return {
    curVisible,
    curEventInfo,
    curNodeEventList,

    onEventModalOk,
    onOpenEventModal,
  }
}
